<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Tiku extends MY_Controller {
	public $left_menu_min;

	function __construct(){
		parent::__construct();
		// $this->left_menu_min = array("menu" => "题库管理", "curr" => $_SERVER['REDIRECT_URL'], "list" => array("科目管理" => "subject", "题库分类" => "/tk_category", "自有题库" => "/tiku", "系统题库" => "/tiku/system", "组卷管理" => "/tiku/test_volume"));
		// $this->smarty->assign("left_menu_min", $this->left_menu_min);
		$parent_id = 4;
		//获取school二级菜单
		$this->load->model('School_manage_menu_model');
	    $menu_list = $this->School_manage_menu_model->get_menu_list($this->is_manage,$parent_id);
	    // print_r($menu_list);exit;
	    $this->smarty->assign("menu_list", $menu_list);

	    $curr = $_SERVER['REDIRECT_URL'];
	    if($curr =='/tiku' || $curr =='/tiku/add_topic' || $curr =='/tiku/import'){
	    	$curr = '/tiku';
	    }else if($curr == "/tiku/test_volume" || strstr($curr,"/tiku/add_test_volume")){
	    	$curr = "/tiku/test_volume";
	    }

		$this->left_menu_min = array("menu" => "题库管理", "curr" => $curr, "list" => $menu_list);
	  	$this->smarty->assign("left_menu_min", $this->left_menu_min);
	  	
		$this->smarty->assign("menu", 'tiku');
	}

	public function index($subject_id = 0, $chapter_id = 0, $type = 0, $source_type = 0, $subject_text = 0, $difficulty_level = 0, $st = 0, $et = 0, $limit = 0){
		$this->load->model("Topics");
		$this->offset = 10;
		if($this->input->post()){
			$limit = 0;
			$post_data = $this->input->post();
			$subject_id = isset($post_data['subject_id']) ? $post_data['subject_id'] : 0;
			$chapter_id = isset($post_data['chapter_id']) ? $post_data['chapter_id'] : 0;
			$type = isset($post_data['type']) ? $post_data['type'] : 0;
			$source_type = isset($post_data['source_type']) ? $post_data['source_type'] : 0;
			$subject_text = $post_data['subject_text'] ? urldecode($post_data['subject_text']) : 0;
			$difficulty_level = !empty($post_data['difficulty_level']) ? $post_data['difficulty_level'] : 0;
			$st = !empty($post_data['st']) ? $post_data['st'] : 0;
            $et = !empty($post_data['et']) ? $post_data['et'] : 0;
		}
		$conditions = array('subject_id' => $subject_id, 'chapter_id' => $chapter_id,'type' => $type, 'source_type' => $source_type, 'subject_text' => $subject_text, 'school_id' => $this->session->userdata['user_data']['school_id'], "difficulty_level" => $difficulty_level);
		$conditions['st'] = $st;
        $conditions['et'] = $et;
		$subject = $this->Topics->get_subject($this->session->userdata['user_data']['school_id']);

		$result = $this->Topics->get_topic_list($limit, $this->offset, $conditions);
		$this->load->library('pagination');
		$current_url = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
		if($chapter_id != 0){
			$chapter_id = str_replace(',', '.', $chapter_id);
		}
		$page_config['base_url'] = '/tiku/index/' . $subject_id . '/' . $chapter_id . '/' . $type . '/' . $source_type . '/' . $subject_text . '/' . $difficulty_level . '/' . $st . '/' . $et;
		$page_config['total_rows'] = $result['count'];
		$page_config['per_page'] = $this->offset;
		$page_config['uri_segment'] = 11;
		$this->pagination->initialize($page_config);
		$pagination = $this->pagination->create_links();
		$this->smarty->assign("conditions", $conditions);
		$this->smarty->assign("topic_list", $result['result']);
		$this->smarty->assign("subject", $subject);
		$this->smarty->assign("menu", "tiku");
		$this->smarty->assign("pagination", $pagination);
		$this->smarty->display("tiku/index.html");
	}

	private function save_analys($analys_data, $qid = 0){
		$data = array();
		foreach ($analys_data['analys_type'] as $key => $value) {
			if($value == 1){ //填空题
				if(!empty($analys_data['subject_text'][$key]) && !empty($analys_data['tk_answer_text'][$key])){
					$data[$key]['analys'] = array("analys_type" => $value, "subject_text" => $analys_data['subject_text'][$key]);
					$data[$key]['analys_result'][] = array("answer_text" => $analys_data['tk_answer_text'][$key]);
				}
			}else{//分录题
				if(!empty($analys_data['subject_text'][$key]) && !empty($analys_data['answer_text'][$key])){
					$data[$key]['analys'] = array("analys_type" => $value, "subject_text" => $analys_data['subject_text'][$key]);
					foreach ($analys_data['answer_text'][$key] as $k => $answer_text) {
						$answer_text = trim($answer_text);
						$type = $analys_data['type'][$key][$k];
						$topic_subject_id = $analys_data['topic_subject_id'][$key][$k];
						$topic_subject_title = $analys_data['topic_subject_title'][$key][$k];
						if(!empty($answer_text) && !empty($type) && !empty($topic_subject_id)){
							$data[$key]['analys_result'][] = array("answer_text" => $answer_text, "type" => $type, "topic_subject_id" => $topic_subject_id, "topic_subject_title" => $topic_subject_title);
						}
					}
				}
			}
		}
		return $data;
	}

	private function save_bdx($bdx_data, $qid = 0){
		$data = array();
		foreach ($bdx_data['subject_text'] as $key => $value) {
			if(!empty($value) && (!empty($bdx_data['checkbox_text'][$key][1]) || !empty($bdx_data['checkbox_text'][$key][2]) || !empty($bdx_data['checkbox_text'][$key][3]) || !empty($bdx_data['checkbox_text'][$key][4])) && (!empty($bdx_data['checkbox'][$key][1]) || !empty($bdx_data['checkbox'][$key][2]) || !empty($bdx_data['checkbox'][$key][3]) || !empty($bdx_data['checkbox'][$key][4]))){
				$data[$key]['subject_text'] = $value;
				$data[$key]['bdx_result'] = array("checkbox_text" => $bdx_data['checkbox_text'][$key], "checkbox" => $bdx_data['checkbox'][$key]);
			}
		}
		return $data;
	}

	function add_topic(){

		$post_data = $this->input->post();
		if($post_data){
			// print_r($post_data);exit;
			$category_info = get_field_by_where("tk_categorys", "name", "id='{$post_data['category_id']}'");
			$area_info = get_field_by_where("areas", "area_name", "area_code='{$post_data['area_code']}'");
			$data['subject_id'] 		= intval($post_data['subject_id']);
			$data['chapter_id'] 		= intval($post_data['chapter_id']);
			$data['type'] 				= intval($post_data['type']);
			$data['difficulty_level'] 	= intval($post_data['difficulty_level']);
			$data['subject_text'] 		= $post_data['subject_text'];
			$data['category_id'] 		= $post_data['category_id'];
			$data['category_name'] 		= $category_info['name'];
			$data['area_code'] 			= $post_data['area_code'];
			$data['area_name'] 			= $area_info['area_name'];
			$data['analysis'] 			= $post_data['analysis'];
			$data['source_type']		= 2;
			$data['school_id'] 			= $this->session->userdata['user_data']['school_id'];
			$data['add_time'] 			= time();
			if($data['type'] == 1){
				if(empty($post_data['an_radio'])){
					show_message($_SERVER['HTTP_REFERER'], "请选择一个正确答案");exit;
				}
				if(empty($post_data['an_radio_text'])){
					show_message($_SERVER['HTTP_REFERER'], "请填写题目答案");exit;
				}
			}elseif($data['type'] == 2){
				if(empty($post_data['an_checkbox'])){
					show_message($_SERVER['HTTP_REFERER'], "请选择一个正确答案");exit;
				}
				if(empty($post_data['an_checkbox_text'])){
					show_message($_SERVER['HTTP_REFERER'], "请填写题目答案");exit;
				}
			}elseif($data['type'] == 3){
				if(empty($post_data['an_choice'])){
					show_message($_SERVER['HTTP_REFERER'], "请选择一个正确答案");exit;
				}
			}elseif($data['type'] == 4){
				if(empty($post_data['analys'])){
					show_message($_SERVER['HTTP_REFERER'], "至少需要一个子题干");exit;
				}
				$analys_data = $this->save_analys($post_data['analys']);
				if(!$analys_data){
					show_message($_SERVER['HTTP_REFERER'], "子题目是空的");
					exit;
				}
			}elseif($data['type'] == 7){
				if(empty($post_data['bdx'])){
					show_message($_SERVER['HTTP_REFERER'], "至少需要一个子题干");exit;
				}
				$bdx_data = $this->save_bdx($post_data['bdx']);
				if(!$bdx_data){
					show_message($_SERVER['HTTP_REFERER'], "子题目是空的");
					exit;
				}
			}elseif($data['type'] == 8 || $data['type'] == 9){
				if(empty($post_data['analysis'])){
					show_message($_SERVER['HTTP_REFERER'], "名词解释、简答题的解析内容不能为空");exit;
				}
			}
			$this->db->insert("tk_topics", $data);
			$insert_id = $this->db->insert_id();
			if($insert_id > 0){
				//插入答案数据
				if($data['type'] == 1){
					foreach ($post_data['an_radio_text'] as $radio_key => $radio_val) {
						$result_data['qid'] = $insert_id;
						$result_data['answer_text'] = $radio_val;
						$result_data['is_right'] =  ( $post_data['an_radio'] == $radio_key) ? 1 : 0;
						$this->db->insert("tk_topic_result", $result_data);
					}
				}elseif($data['type'] == 2){
					foreach ($post_data['an_checkbox_text'] as $checkbox_key => $checkbox_val) {
						$result_data['qid'] = $insert_id;
						$result_data['answer_text'] = $checkbox_val;
						$result_data['is_right'] =  ( isset($post_data['an_checkbox'][$checkbox_key])) ? 1 : 0;
						$this->db->insert("tk_topic_result", $result_data);
					}
				}elseif($data['type'] == 3){
					$result_data['qid'] = $insert_id;
					$result_data['answer_text'] = '正确';
					$result_data['is_right'] =  ( $post_data['an_choice'] == 1) ? 1 : 0;
					$this->db->insert("tk_topic_result", $result_data);

					$result_data['qid'] = $insert_id;
					$result_data['answer_text'] = '错误';
					$result_data['is_right'] = ( $post_data['an_choice'] == 2) ? 1 : 0;
					$this->db->insert("tk_topic_result", $result_data);
				}elseif($data['type'] == 4){
					foreach ($analys_data as $key => $topic_analys_data) {
						$topic_analys_data['analys']['qid'] = $insert_id;
						$this->db->insert("tk_topic_analys", $topic_analys_data['analys']);
						$aid = $this->db->insert_id();
						$topic_analys_result_data = array();
						foreach ($topic_analys_data['analys_result'] as $k => $topic_analys_result) {
							$topic_analys_result['aid'] = $aid;
							$topic_analys_result['qid'] = $insert_id;
							$topic_analys_result_data[] = $topic_analys_result;
						}
						$this->db->insert_batch("tk_topic_analys_result", $topic_analys_result_data);
					}
				}elseif($data['type'] == 7){
					$topic_bdx_result_data = array();
					foreach ($bdx_data as $key => $topic_bdx_data) {
						$topic_bdx_data['analys']['qid'] = $insert_id;
						$topic_bdx_data['analys']['subject_text'] = $topic_bdx_data['subject_text'];
						$this->db->insert("tk_topic_analys", $topic_bdx_data['analys']);
						$aid = $this->db->insert_id();
						
						foreach ($topic_bdx_data['bdx_result']['checkbox_text'] as $k => $answer_text) {
							$topic_bdx_result['aid'] = $aid;
							$topic_bdx_result['qid'] = $insert_id;
							$topic_bdx_result['answer_text'] = $answer_text;
							if(!empty($topic_bdx_data['bdx_result']['checkbox'][$k])){
								$topic_bdx_result['is_right'] = 1;
							}else{
								$topic_bdx_result['is_right'] = 0;
							}
							$topic_bdx_result_data[] = $topic_bdx_result;
						}
					}
					$this->db->insert_batch("tk_topic_analys_result", $topic_bdx_result_data);
				}
				show_message($_SERVER['HTTP_REFERER']);
			}else{
				show_message($_SERVER['HTTP_REFERER'], "操作失败");
			}
		}else{
			$this->load->model("Topics");
			$this->load->model("Areas");
			$this->load->model("Tk_categorys");
			$province_list = $this->Areas->get_province_data();
			$cagetory_list = $this->Tk_categorys->get_category_data($this->user_data['school_id']);
			$subject = $this->Topics->get_subject($this->user_data['school_id']);
			$this->smarty->assign("subject", $subject);
			$this->smarty->assign("province_list", $province_list);
			$this->smarty->assign("cagetory_list", $cagetory_list);
			$this->smarty->assign("menu", "tiku");
			$this->smarty->assign("post_url", '/tiku/add_topic');
			$this->smarty->display("tiku/add_topic.html");
		}
	}

	function edit_topic($id = 0){
			$post_data = $this->input->post();
			if($post_data){
				$category_info 				= get_field_by_where("tk_categorys", "name", "id='{$post_data['category_id']}'");
				$area_info 					= get_field_by_where("areas", "area_name", "area_code='{$post_data['area_code']}'");
				$data['subject_id'] 		= intval($post_data['subject_id']);
				$data['chapter_id'] 		= intval($post_data['chapter_id']);
				$data['difficulty_level'] 	= intval($post_data['difficulty_level']);
				$data['category_id'] 		= $post_data['category_id'];
				$data['category_name'] 		= $category_info['name'];
				$data['area_code'] 			= $post_data['area_code'];
				$data['area_name'] 			= $area_info['area_name'];
				$data['analysis'] 			= $post_data['analysis'];
				$this->db->where('id', $post_data['id']);
				$this->db->update('tk_topics', $data);
				if($this->db->affected_rows() > 0){
					show_message($_SERVER['HTTP_REFERER']);
				}else{
					show_message($_SERVER['HTTP_REFERER'], "操作失败");
				}
			}else{
				if(intval($id) > 0){
					$topic_info = get_field_by_where("tk_topics", "*", "id='{$id}'");
					if(!$topic_info){
						show_message("/news/type_list", "数据不存在");exit;
					}
					$this->load->model("Topics");
					$this->load->model("Areas");
					$this->load->model("Tk_categorys");
					$subject = $this->Topics->get_subject($this->user_data['school_id']);
					$province_list = $this->Areas->get_province_data();
					$cagetory_list = $this->Tk_categorys->get_category_data($this->user_data['school_id']);
					$chapter_list_data = $this->get_chapter_list($topic_info['subject_id']);
					if($topic_info['type'] == 4 || $topic_info['type'] == 7){
						$topic_result = $this->Topics->get_topic_analys($id);
						if($topic_result){
							foreach ($topic_result as $key => $value) {
								$topic_result[$key]['result'] = $this->Topics->get_topic_analys_result($value['id']);
							}
						}
					}else{
						$topic_result = $this->Topics->get_topic_reuslt($id);
					}
					$letter = array('A','B','C','D');
					$this->smarty->assign("topic_info", $topic_info);
					$this->smarty->assign("action", '编辑题目');
					$this->smarty->assign("subject", $subject);
					$this->smarty->assign("province_list", $province_list);
					$this->smarty->assign("cagetory_list", $cagetory_list);
					$this->smarty->assign("post_url", '/tiku/edit');
					$this->smarty->assign("chapter_list_data", $chapter_list_data);
					$this->smarty->assign("topic_result", $topic_result);
					$this->smarty->assign("letter", $letter);
					$this->smarty->assign("menu", "tiku");
					$this->smarty->assign("post_url", '/tiku/edit_topic');
					$this->smarty->display("tiku/add_topic.html");
				}else{
					show_message("/news", "非法操作");
				}
			}
		}

	function delete_topic($id = 0){
		if($id > 0){
			$topic_info = get_field_by_where("tk_topics", "id,school_id", "id='{$id}'");
			if($topic_info){
				if($topic_info['school_id'] != $this->session->userdata['user_data']['school_id']){
					show_message($this->jump_url, "很抱歉，您无法删除该题目！");
				}else{
					$this->db->where("id", $id);
					$this->db->delete("tk_topics");
					show_message($this->jump_url);
				}
			}else{
				show_message($this->jump_url, "数据不存在");
			}
		}else{
			show_message($this->jump_url, "非法操作");
		}
	}

	function test_volume($subject_id = 0, $test_volume_name = 0, $st = 0, $et = 0, $limit = 0){
		$this->left_menu_min['curr'] = '/tiku/test_volume';
		$this->offset = 10;
		if($this->input->post()){
			$limit = 0;
			$post_data = $this->input->post();
			$test_volume_name = $post_data['test_volume_name'] ? urldecode($post_data['test_volume_name']) : 0;
			$subject_id = isset($post_data['subject_id']) ? $post_data['subject_id'] : 0;
			$st = !empty($post_data['st']) ? $post_data['st'] : 0;
            $et = !empty($post_data['et']) ? $post_data['et'] : 0;
		}
		$this->load->model("Topics");
		$conditions = array('subject_id' => $subject_id, 'test_volume_name' => $test_volume_name, 'school_id' => $this->session->userdata['user_data']['school_id']);
		$conditions['st'] = $st;
        $conditions['et'] = $et;
		$this->load->model("Test_volumes");
		$result = $this->Test_volumes->get_test_volume_list($limit, $this->offset, $conditions);
		if($result['count'] > 0){
			$conditions['school_id'] = $this->session->userdata['user_data']['school_id'];
			foreach ($result['result'] as $key => $value) {
				$conditions['volume_id'] = $value['id'];
				$publish_list = $this->Test_volumes->get_test_volume_publish(0, 0, $conditions);
				if(!empty($publish_list)){
					foreach ($publish_list as $k => $value) {
						$result['result'][$key]['type'][$value['type']] = 1;
					}
				}
			}
		}
		// print_r($result['result']);   
		$this->load->library('pagination');
		$page_config['base_url'] = '/tiku/test_volume/' . $subject_id . '/' . $test_volume_name;
		$page_config['total_rows'] = $result['count'];
		$page_config['per_page'] = $this->offset;
		$page_config['uri_segment'] = 7;
		$this->pagination->initialize($page_config);
		$pagination = $this->pagination->create_links();
		$subject = $this->Topics->get_subject($this->session->userdata['user_data']['school_id']);
		$this->smarty->assign("subject", $subject);
		$this->smarty->assign("test_volume_list", $result['result']);
		$this->smarty->assign("conditions", $conditions);
		$this->smarty->assign("pagination", $pagination);
		$this->smarty->assign("menu", "tiku");
		$this->smarty->display("tiku/test_volume.html");
	}

	function add_test_volume($subject_id = 0, $test_volume_name = ''){
		$this->load->model("Topics");
		$school_id = $this->session->userdata['user_data']['school_id'];
		$teacher_id = $this->session->userdata['user_data']['teacher_id'];

		$post_data = $this->input->post();
		if($post_data){
			if(empty($post_data['template_id'])){
				show_message($this->jump_url, "缺少模版ID");
				exit;
			}

			$template_info = get_field_by_where("tk_test_volume_templates", "*", "id='{$post_data['template_id']}'");
			
			if(!$template_info){
				show_message($this->jump_url, "组卷模版不存在");
				exit;
			}
			if($template_info['school_id'] != $school_id){
				show_message($this->jump_url, "您无法使用该模版");
				exit;
			}

			$test_volume_data['name'] = trim($post_data['name']);
			$test_volume_data['school_id'] = $school_id;
			$test_volume_data['teacher_id'] = $teacher_id;
			$test_volume_data['subject_id'] = intval($post_data['subject_id']);
			$test_volume_data['topic_source'] = intval($post_data['topic_source']) + 1;
			$test_volume_data['create_topic_type'] = intval($post_data['create_topic_type']);
			$test_volume_data['topic_info'] = !empty($post_data['topic']) ? implode(",", $post_data['topic']) : '';
			$test_volume_data['chapter_id'] = !empty($post_data['chapter_id']) ? implode(",", $post_data['chapter_id']) : '';
			$test_volume_data['template_id'] = intval($post_data['template_id']);

			//系统随机选题
			if($post_data['create_topic_type'] == 1){
				$template_content = json_decode($template_info['content'], true);
				$conditions['school_id'] = $test_volume_data['school_id'];
				$conditions['subject_id'] = $test_volume_data['subject_id'];
				foreach ($template_content as $key => $value) {
					for ($i=0; $i < $value['number']; $i++) {
						$conditions['notin_ids'] = $test_volume_data['topic_info'];
						$rand_data = $this->Topics->get_rand_topic($conditions);
						if($rand_data){
							$test_volume_data['topic_info'][] = $rand_data['id'];
						}
					}
				}
				if(is_array($test_volume_data['topic_info']) && count($test_volume_data['topic_info']) > 0){
					$test_volume_data['topic_info'] = implode(",", $test_volume_data['topic_info']);
				}else{
					show_message("/tiku/add_test_volume", "所选的科目下没有可用题目");exit;
				}
			}else{//自己选题
				if($template_info['total_topic'] != count($post_data['topic'])){
					// echo '您选的题目数量跟组卷模版不符';exit;
				}
			}
			$letter = array('A','B','C','D');
			$topic_list = $this->pretend_topics($test_volume_data);
			// print_r($topic_list);exit;
			$this->smarty->assign("test_volume_data", $test_volume_data);
			$this->smarty->assign("topic_list", $topic_list);
			$this->smarty->assign("letter", $letter);
			$this->smarty->display("tiku/test_volume_topic_list.html");
		}else{
			$subject = $this->Topics->get_subject($school_id);
			if($subject_id == 0){
				if(empty($subject)){
					show_message("/subject/add", "请先添加科目");exit;
				}
				$chapter_list_data = $this->get_chapter_list($subject[0]['id']);
			}else{
				$chapter_list_data = $this->get_chapter_list($subject_id);
			}
			$templates = $this->Topics->get_test_volume_templates($school_id);
			$this->smarty->assign("subject", $subject);
			$this->smarty->assign("subject_id", $subject_id);
			$this->smarty->assign("test_volume_name", urldecode($test_volume_name));
			$this->smarty->assign("chapter_list_data", $chapter_list_data);
			$this->smarty->assign("templates", $templates);
			$this->smarty->assign("menu", "tiku");
			$this->smarty->display("tiku/add_test_volume.html");
		}
	}

	//组装题目
	function pretend_topics($test_volume_data = array()){
		$topic_list = array();
		if($test_volume_data){
			$topic_info_list = $this->Topics->get_topic_by_id($test_volume_data['topic_info']);
			if($topic_info_list){
				foreach ($topic_info_list as $key => $value) {
					if($value['type'] == 4 || $value['type'] == 7){
						$analy_result = $this->Topics->get_topic_analys($value['id']);
						if($analy_result){
							$value['result'][$key] = $analy_result;
							foreach ($analy_result as $k => $v) {
								$value['result'][$key][$k]['answer_list'] = $this->Topics->get_topic_analys_result($v['id']);
							}
							$topic_list[$value['type']][] = $value;
						}
					}else{
						$value['result'] = $this->Topics->get_topic_result_by_id($value['id']);
						$topic_list[$value['type']][] = $value;
					}
					/*foreach ($topic_result as $k => $v) {
						if($v['qid'] == $value['id']){
							$value['result'][] = $v;
							unset($topic_result[$k]);
						}
					}*/
				}
			}
		}
		return $topic_list;
	}


	/*function pretend_topics($test_volume_data = array()){
		$topic_list = array();
		if($test_volume_data){
			$topic_info_list = $this->Topics->get_topic_by_id($test_volume_data['topic_info']);
			if($topic_info_list){
				$topic_result = $this->Topics->get_topic_result_by_id($test_volume_data['topic_info']);
				foreach ($topic_info_list as $key => $value) {
					foreach ($topic_result as $k => $v) {
						if($v['qid'] == $value['id']){
							$value['result'][] = $v;
							unset($topic_result[$k]);
						}
					}
					$topic_list[$value['type']][] = $value;
				}
			}
		}print_r($topic_list);
		return $topic_list;
	}*/
	//保存组卷
	function save_test_volume(){
		$post_data = $this->input->post();
		if($post_data){
			if(isset($post_data['analys'])) unset($post_data['analys']);
			$post_data['add_time'] = time();
			$this->db->insert("tk_test_volumes", $post_data);
			show_message("/tiku/test_volume");
		}
	}

	function get_chapter_list($subject_id = 0){
		$conditions = array();
		if($subject_id > 0){
			$conditions['subject_id'] = $subject_id;
		}
		$chapter_list = $this->Topics->get_chapter($conditions);

		$chapter_list_data_sort = $chapter_list_data = array();
		$code = 0;
		$keys = array();
		if($chapter_list){
			$sort = array();
			foreach ($chapter_list as $key => $value) {
				if($value['parent_id'] == 0){
					$chapter_list_data_sort[$value['id']] = $value;
					$keys[$value['id']] = 1;
					$sort[] = $value['sort'];
					unset($chapter_list[$key]);
				}
			}
			array_multisort($sort, SORT_ASC, $chapter_list_data_sort);
			foreach($chapter_list_data_sort as $key => $value){
				$chapter_list_data[$value['id']] = $value;
			}


			foreach ($chapter_list as $key => $value) {
				if(isset($chapter_list_data[$value['parent_id']])){
					$chapter_list_data[$value['parent_id']]['sub'][$value['id']] = $value;
					unset($chapter_list[$key]);
				}
			}

			if($chapter_list AND $chapter_list_data){
				foreach ($chapter_list_data as $key => $value) {
					if(isset($value['sub'])){
						foreach ($value['sub'] as $k => $v) {
							foreach ($chapter_list as $k1 => $v1) {
								if($k == $v1['parent_id']){
									$chapter_list_data[$key]['sub'][$k]['sub'][$v1['id']] = $v1;
								}
							}
						}
					}
				}
			}
		}
		/*$data = array();
		if(count($keys) > 0){
			ksort($keys);
			foreach ($keys as $k => $v) {
				$data[$k] = $chapter_list_data[$k];
			}
		}*/
		return $chapter_list_data;
	}

	function get_list($source_type = 0, $subject_id = 0, $chapter_id= 0, $type = 0, $subject_text = 0, $limit = 0){
		$this->load->model("Topics");
		if($this->input->post()){
			$subject_text = $this->input->post('subject_text',TRUE) ? urldecode($this->input->post('subject_text',TRUE)) : 0;
			$type = $this->input->post('type');
			$limit = 0;
		}
		if($chapter_id != 0){
			$chapter_id = str_replace('.', ',', $chapter_id);
		}
		$subject_text = urldecode($subject_text);
		$conditions['source_type'] = $source_type;
		$conditions['subject_id'] = $subject_id;
		$conditions['chapter_id'] = $chapter_id;
		$conditions['type'] = $type;
		$conditions['subject_text'] = $subject_text;
		$conditions['school_id'] = $this->session->userdata['user_data']['school_id'];
		$offset = 10;
		$result = $this->Topics->get_topic_list($limit, $offset, $conditions);
		$this->load->library('pagination');
		$current_url = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
		if($chapter_id != 0){
			$chapter_id = str_replace(',', '.', $chapter_id);
		}
		$page_config['base_url'] = '/tiku/get_list/' . $source_type . '/' . $subject_id . '/' . $chapter_id . '/' . $type . '/' . $subject_text;
		$page_config['total_rows'] = $result['count'];
		$page_config['per_page'] = $offset;
		$page_config['uri_segment'] = 8;
		$this->pagination->initialize($page_config);
		$pagination = $this->pagination->create_links();
		$this->smarty->assign("current_url", $current_url);
		$this->smarty->assign("topic_list", $result['result']);
		$this->smarty->assign("pagination", $pagination);
		$this->smarty->assign("conditions", $conditions);
		$this->smarty->assign("action", '题目列表');
		$this->smarty->display("tiku/list.html");
	}

	function save_test_volume_template(){
		$school_id = $this->session->userdata['user_data']['school_id'];
		$teacher_id = $this->session->userdata['user_data']['teacher_id'];

		$post_data = $this->input->post();
		if(empty($post_data['template_name'])){
			$error = 1;
			$msg = '缺少模版名称';
			echo json_encode(array("error" => $error, "msg" => $msg));exit;
		}
		$template_info = get_field_by_where("tk_test_volume_templates", "id", "template_name='{$post_data['template_name']}' AND teacher_id = $teacher_id");
		if($template_info){
			$error = 1;
			$msg = '模版名重复';
			echo json_encode(array("error" => $error, "msg" => $msg));exit;
		}
		if(isset($post_data['number']) && isset($post_data['fraction'])){
			$data['template_name'] 	= trim($post_data['template_name']);
			$data['school_id'] 		= $school_id;
			$data['teacher_id'] 	= $teacher_id;
			$data['total_fraction'] = 0;
			$data['total_topic'] 	= 0;
			$data['content'] 		= array();
			$data['add_time'] 		= time();
			$tpoic_type = array("1" => "单选题", "2" => "多选题", "3" => "判断题", "4" => "计算分析题", "7" => "不定向选择题", "8" => "名词解释", "9" => "简答题");
			foreach ($post_data['number'] as $key => $value) {
				if($value > 0){
					$data['total_fraction'] += $fraction = $value * $post_data['fraction'][$key];
					$data['total_topic'] += $value;
					$data['content'][$key] = array("name" => $tpoic_type[$key], "number" => $value, "fraction" => $post_data['fraction'][$key]);
				}
			}
			if(count($data['content']) > 0 && $data['total_topic'] > 0){
				$data['content'] = json_encode($data['content']);
				$this->db->insert("tk_test_volume_templates", $data);
				$error = 0;
				$msg = '模版保存成功';
				$template_id = $this->db->insert_id();
				echo json_encode(array("error" => $error, "msg" => $msg, "template_id" => $template_id, 'template_name' => $data['template_name']));exit;
			}else{
				$error = 1;
				$msg = '缺少模版内容';
				echo json_encode(array("error" => $error, "msg" => $msg));exit;
			}
		}else{
			$error = 1;
			$msg = '缺少模版内容';
			echo json_encode(array("error" => $error, "msg" => $msg));exit;
		}
	}

	function get_template_content(){
		$post_data = $this->input->post();
		$template_info = get_field_by_where("tk_test_volume_templates", "content", "id='{$post_data['template_id']}'");
		if($template_info){
			$error = 0;
			echo json_encode(array("error" => $error, "content" => json_decode($template_info['content'])));exit;
		}else{
			$error = 1;
			$msg = '模版不存在';
			echo json_encode(array("error" => $error, "msg" => $msg));exit;
		}
	}

	function get_chapter_list_data($subject_id){
		$this->load->model("Topics");
		$conditions['subject_id'] = $subject_id;
		$chapter_list = $this->Topics->get_chapter($conditions);
		$chapter_list_data = array();
		$code = 0;
		$keys = array();
		if($chapter_list){
			foreach ($chapter_list as $key => $value) {
				if($value['parent_id'] == 0){
					$chapter_list_data[$value['id']] = $value;
					$keys[$value['id']] = 1;
					unset($chapter_list[$key]);
				}
			}

			foreach ($chapter_list as $key => $value) {
				if(isset($chapter_list_data[$value['parent_id']])){
					$chapter_list_data[$value['parent_id']]['sub'][$value['id']] = $value;
					unset($chapter_list[$key]);
				}
			}

			if($chapter_list AND $chapter_list_data){
				foreach ($chapter_list_data as $key => $value) {
					if($value['sub']){
						foreach ($value['sub'] as $k => $v) {
							foreach ($chapter_list as $k1 => $v1) {
								if($k == $v1['parent_id']){
									$chapter_list_data[$key]['sub'][$k]['sub'][$v1['id']] = $v1;
								}
							}
						}
					}
				}
			}
		}
		$data = array();
		if(count($keys) > 0){
			ksort($keys);
			foreach ($keys as $k => $v) {
				$data[$k] = $chapter_list_data[$k];
			}
		}
		return $data;
	}

	function ignore_get_subject_chapter(){
		$post_data = $this->input->post();
		if(is_ajax_request()){
			$chapter_list_data = $this->get_chapter_list_data($post_data['subject_id']);
			$code = 0;
			if($chapter_list_data){
				$code = 1;
			}
			echo json_encode(array("code" => $code, "chapter_list" => $chapter_list_data));
		}
	}

	//1：发布到真题冲刺，2：发布到考情速递，3：真题和考情都已经发布
	function publish_volume(){
		$post_data = $this->input->post();
		if(is_ajax_request()){
			$volume_info = get_field_by_where("tk_test_volumes", "id, publish_status", "id='{$post_data['volume_id']}'");
			if(!$volume_info){
				$error = 1;
				$msg = '对不起，您操作的组卷信息不存在！';
			}else{
				$update_data = array();
				$type = $post_data['type'];
				if($type == 'zt'){
					$update_data['zt_timeout'] = intval($post_data['timeout']);
					$update_data['publish_status'] = 1;
					if($volume_info['publish_status'] == 2){
						$update_data['publish_status'] = 3;
					}
					$this->db->where("id", intval($post_data['volume_id']));
					$this->db->update("tk_test_volumes", $update_data);
					$error = 0;
					$msg = '已发布到真题冲刺';
				}elseif($type = 'kq'){
					$update_data['kq_timeout'] = intval($post_data['timeout']);
					$update_data['publish_status'] = 2;
					if($volume_info['publish_status'] == 1){
						$update_data['publish_status'] = 3;
					}
					$this->db->where("id", intval($post_data['volume_id']));
					$this->db->update("tk_test_volumes", $update_data);
					$error = 0;
					$msg = '已发布到考情速递';
				}else{
					$error = 1;
					$msg = '非法操作';
				}
			}
		}else{
			$error = 1;
			$msg = '非法操作';
		}

		echo json_encode(array("error" => $error, "msg" => $msg));
	}

	function system($limit = 0){
		$this->load->model("Topics");
		$result = $this->Topics->get_school_system_topics($this->session->userdata['user_data']['school_id'], $limit, $this->offset = 10);

		$this->load->library('pagination');
		$current_url = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];

		$page_config['base_url'] = '/tiku/system';
		$page_config['total_rows'] = $result['count'];
		$page_config['per_page'] = $this->offset;
		$page_config['uri_segment'] = 3;
		$this->pagination->initialize($page_config);
		$pagination = $this->pagination->create_links();
		$this->smarty->assign("system_topic_list", $result['result']);
		$this->smarty->assign("pagination", $pagination);
		$this->smarty->display("tiku/system.html");
	}

	function system_topic_code($category_id = 0, $limit = 0){
		$this->load->model("Topics");
		$result = $this->Topics->get_school_system_topic_codes($this->session->userdata['user_data']['school_id'], $category_id, $limit, $this->offset = 10);

		$this->load->library('pagination');
		$current_url = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];

		$page_config['base_url'] = '/tiku/system_topic_code/'.$category_id;
		$page_config['total_rows'] = $result['count'];
		$page_config['per_page'] = $this->offset;
		$page_config['uri_segment'] = 4;
		$this->pagination->initialize($page_config);
		$pagination = $this->pagination->create_links();
		$this->smarty->assign("system_topic_list", $result['result']);
		$this->smarty->assign("pagination", $pagination);
		$this->smarty->display("tiku/system_topic_code.html");
	}

	function import(){
		$this->smarty->display("tiku/import.html");
	}

	function test_volume_publish($volume_id, $type){
		if(empty($volume_id) || empty($type)){
			show_error("非法操作");exit;
		}
		$start_time = $end_time = 0;
		if($_POST){
			$post_data = $this->input->post();
			if(!empty($post_data['start_time'])){
				$start_time = $post_data['start_time'];
			}
			if(!empty($post_data['end_time'])){
				$end_time = $post_data['end_time'];
			}
		}
		$volume_info = get_field_by_where("tk_test_volumes", "*", "id='{$volume_id}'");
		$this->load->model("Topics");
		$school_id = $this->session->userdata['user_data']['school_id'];
		$teacher_id = $this->session->userdata['user_data']['teacher_id'];
		// $subject = $this->Topics->get_subject();
		// $chapter_list_data = $this->get_chapter_list($subject[0]['id']);
		$templates = $this->Topics->get_test_volume_templates($school_id);
		$this->load->model('Classo2o_model');
		$this->smarty->assign("class_list", '');
		$classes = $this->Classo2o_model->get_class_list($this->user_data['school_id'], $start_time, $end_time);
		$this->smarty->assign("classes", $classes);
		$this->smarty->assign("start_time", $start_time);
		$this->smarty->assign("end_time", $end_time);
		$this->smarty->assign("volume_id", $volume_id);
		$this->smarty->assign("type", $type);
		$this->smarty->assign("templates", $templates);
		$this->smarty->assign("menu", "classes");
		$this->smarty->display("tiku/test_volume_publish.html");
	}

	function save_volume_publish(){
		$post_data = $this->input->post();
		$msg = '';
		$error = 0;

		if(empty($post_data['volume_id'])){
			$error = 1;
			$msg = '缺少组卷ID';
		}
		if(empty($post_data['type'])){
			$error = 1;
			$msg = '缺少发布类型TYPE';
		}
		if(empty($post_data['classes']) && ($post_data['type'] == 3 || $post_data['type'] ==4)){
			$error = 1;
			$msg = '至少需要发布到一个班级';
		}
		if(empty($post_data['timeout'])){
			$error = 1;
			$msg = '未指定考试时长';
		}
		if(empty($post_data['name'])){
			$error = 1;
			$msg = '缺少名称';
		}
		/*if(($post_data['type'] == 3 || $post_data['type'] ==4) && (empty($post_data['start_time']) || empty($post_data['end_time']))){
			$error = 1;
			$msg = '未指定考试时间';
		}*/
		$volume_info = get_field_by_where("tk_test_volumes", "*", "id='{$post_data['volume_id']}'");
		if(empty($volume_info)){
			$error = 1;
			$msg = '组卷数据不存在';
		}
		$post_data['school_id'] = $this->user_data['school_id'];
		$post_data['teacher_id'] = $this->session->userdata['user_data']['teacher_id'];
		if(!empty($post_data['classes'])){
			$post_data['classes'] = implode(",", $post_data['classes']);
		}
		/*if(!empty($post_data['start_time'])){
			$post_data['start_time'] = strtotime($post_data['start_time']);
		}
		if(!empty($post_data['end_time'])){
			$post_data['end_time'] = strtotime($post_data['end_time']);
		}*/
		$post_data['add_time'] = time();
		if($post_data['type'] == 3 || $post_data['type'] == 4){
			$this->load->model('Classo2o_model');
			if($error == 0){
				$this->db->insert("tk_test_volumes_publish", $post_data);
				$user_list = $this->Classo2o_model->get_classes_user_openid($post_data['classes']);
				if($user_list){
					foreach ($user_list as $key => $value) {
						if($post_data['type'] == 3){
							$template_id = 'lqys63GSbWsnbumTU4DfgIQVwuE_2VE_x_gIsUTbWeI';
							$data = array(
										"first" 	=> array("value" => '亲爱的同学，您有新的作业提醒，请查阅。'),
										"keyword1" 	=> array("value" => "-"),
										"keyword2"	=> array("value" => $post_data['name']),
										"keyword3"	=> array("value" => '作业标准完成时长为：' . $post_data['timeout'] . '分钟，请自行计时。'),
										"remark"	=> array("value" => $post_data['prompt'])
									);
						}else{
							$template_id = '6hY9F0nfOfohnpEXtA1OuDMoJePbnGNSdZocNyakFOI';
							$data = array(
										"first" 	=> array("value" => '亲爱的同学，您有新的考试提醒，请查阅。'),
										"keyword1" 	=> array("value" => $post_data['name']),
										"keyword2"	=> array("value" => '-'),
										"keyword3"  => array("value" => "不限"),
										"keyword4"	=> array("value" => $value['course_name']),
										"keyword5"	=> array("value" => '互联网自主考试'),
										"remark"	=> array("value" => '考试标准完成时长为：' . $post_data['timeout'] . '分钟，请自行计时。' . $post_data['prompt'])
									);
						}
						$this->wx_notice($value['open_id'], $template_id, $data);
					}
				}
			}else{
				$this->smarty->assign("class_list", '');
				$this->smarty->assign("volume_id", $post_data['volume_id']);
				$this->smarty->assign("type", $post_data['type']);
				$classes = $this->Classo2o_model->get_class_list($this->user_data['school_id']);
				$this->smarty->assign("classes", $classes);
			}
			$this->smarty->assign("ok", 1);
			$this->smarty->assign("error", $error);
			$this->smarty->assign("msg", $msg);
			$this->smarty->assign("type", $post_data['type']);
			$this->smarty->display("tiku/test_volume_publish.html");
		}else{
			$this->db->insert("tk_test_volumes_publish", $post_data);
			if($post_data['type'] == 1){
				$result['msg'] = "已发布到考情速递";
			}else if($post_data['type'] == 2){
				$result['msg'] = "已发布到真题冲刺";
			}
			$result['error'] = 0;
			echo json_encode($result);
		}
		// show_message("/tiku/save_volume_publish/1");
	}

	function wx_notice($touser, $template_id, $data){
		require_once "third_party/wxjsapi/wxapi_utils.php";
		$wxapi_sccesstoken = new Wxapi_Utils($this->user_data['school_id']);
		$sccesstoken = $wxapi_sccesstoken->getAccessToken();
		$req_url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $sccesstoken;
		$wx_data = array(
						"touser" => $touser,
						"template_id" => $template_id,
						// "url" => "http://test.deanxin.com",
						"data" => $data
					);
		$result = curlRequest($req_url, $wx_data, "POST", TRUE);
		return $result;
	}

	function delete_volume($volume_id = 0){
		$volume_info = get_field_by_where('tk_test_volumes', "id,school_id", "id='{$volume_id}'");
		if(!$volume_info){
			show_message("/tiku/test_volume", "数据不存在");exit;
		}
		if($this->session->userdata['user_data']['school_id'] != $volume_info['school_id']){
			show_message("/tiku/test_volume", "无法删除");exit;
		}
		$this->load->model("Test_volumes");
		$this->Test_volumes->delete_volume_data($volume_id);
		show_message("/tiku/test_volume", "删除成功");exit;
	}

	function delete($ids = 0){
		if($_POST){
			$ids = $this->input->post('ids');
		}else{
			$ids = (array) $ids;
		}
		delete_data($ids, "tk_topics");
		if($this->db->affected_rows() > 0){
			show_message($_SERVER['HTTP_REFERER'], "删除成功");
		}else{
			show_message($_SERVER['HTTP_REFERER'], "删除失败，请重试！");
		}
	}
}